package com.atguigu.springcloud.service;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 孙志鹏
 * @createDate 2022/4/6 12:03
 */
@Component
public class MyLb implements LoadBalanced{

    // 线程安全的计数器，进行自增自减
    private AtomicInteger atomicInteger = new AtomicInteger();

    public final int getAndIncrement() {
        // 1. 声明一个值是多少
        int current;
        // 2. 声明下一个值是多少
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0:current + 1;
        } while(!this.atomicInteger.compareAndSet(current,next));
        System.out.println("第几次访问: next: " + next);
        return next;
    }

    /**
     * 当前服务的总服务数量
     * @param serviceInstanceList
     * @return
     */
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstanceList) {
        int index = getAndIncrement() % serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }
}
